<template>
	<view class="main" v-if="Object.keys(user).length > 0">
		<!--  -->
		<!-- <view class="animated-element"></view> -->
		<scroll-view class="scroll" :scroll-top="scrollTop" :scroll-into-view="viewId" scroll-y="true" :style="{ height: `${scrollViewHeight}px` }" @click="TouchMain">
			<view v-if="showJoinAnimation" class="animated-element">
				<image class="imgs" :src="jionUser.nicPic" mode=""></image>
				<text class="texts">{{ jionUser.nicName }}</text>
				<text class="texts">进来了</text>
			</view>
			<view v-if="msglist && msglist.length > 0" v-for="(item, index) in msglist" :key="index">
				<view class="timeformat" v-if="isTimeshow(index)">
					<view class="" style="padding-right: 25rpx">{{ formatMessageTime(item.timestamp) }}</view>
					<view v-if="item" class="">
						{{ formatDistance(item) }}
					</view>
					<view v-else class="">定位中....</view>
				</view>
				<view class="item" :class="item.userTel === user.userTel ? 'push' : 'pull'" :id="`msgall-${item.timestamp}`">
					<image :src="item.nicPic" mode="aspectFill" class="pic" @click="handleAddFriend(item)"></image>
					<view class="" style="display: flex; flex-direction: column;position: relative;" @longpress="showDeleteMenu(item, index)">
						<view class="userId" v-if="user.userTel !== item.userTel">
							{{ item.nicName ? item.nicName : item.sendUserId }}
						</view>
						<view class="content" v-if="item.messageType === 1" :id="`msg-${item.timestamp}`">
							<view class="progress-bar" :style="{ width: (item.content.duration < 6 ? 100 : item.content.duration * 10) + 'rpx' }" @click.stop="handonPlay(index)">
								{{ stateConfig.isplay === index ? progressPercent.toFixed(0) + '%' : item.content.duration + '秒' }}
								<view v-if="stateConfig.isplay === index" class="progress" :style="{ width: progressPercent + '%' }"></view>
							</view>
						</view>

						<view class="content" v-if="item.messageType === 2">
							{{ item.content.text }}
						</view>

						<view class="media" v-else-if="item.messageType === 3" @click="preview(index)">
							<image  :src="item.content.mediaPath" mode="aspectFit"></image>
						</view>
						<view class="video-thumbnail" v-else-if="item.messageType === 6">
							<view class="image-container">
								<image class="video_v" :src="item.content.videoPic" mode="aspectFill" />
								<image class="mark-image" @click="videoplay(item.content.videoPath)" src="/static/play.png" mode="aspectFit" />
							</view>
						</view>
							<view v-if="showDeleteConfirm === index" class="msgEdit">
						<view @click="deleteMessage(item, index)">删除</view>
					</view>
					</view>
					<view v-if="!item.isSended" class="unsend" @click="reSendMsg(item)">
						<view class="">未发送</view>
						<image src="/static/unsend.png" mode="aspectFit"></image>
					</view>
				
				</view>
			</view>

			<!-- 可移动视图，添加了尺寸、背景和过渡效果 -->
		</scroll-view>

		<groupToolTab v-show="Object.keys(group).length > 0" :groupId="group.groupId"></groupToolTab>
		<groupNavBar v-if="Object.keys(group).length > 0" :members="members" :group="group" :own="own"></groupNavBar>
		<!-- <inputTab :isMute="Imember.isMute"  v-if="isInputShow" @sendText="sendText" @Video="msg_video" @Images="media_msg" @hangdleInputshow="hangdleInputshow"></inputTab> -->
		<groupInfo v-show="groupInfoShow" :groupInfo="group" :own="own"></groupInfo>
		<recordVioce class="recordVioce" @handleclose="recordVioceClose" @voice_msg="voice_msg" v-if="isSpeak"></recordVioce>
		<addFriend v-if="isAddFriend" :isAddFriend="isAddFriend" :userInfo="userInfo" @close="isAddFriend = false"></addFriend>

	</view>
</template>

<script>
// import inputTab from '../../components/inputTab.vue';
import groupInfo from '../../components/groupInfo.vue';
import groupToolTab from '../../components/groupToolTab.vue';
import { eventBus } from '../../utils/eventBus';
import { sendText, voiceMsg, mediaMsg, videoMsg,reSendMsg } from '../../methods/msgSend.js';
import { initMsgData } from '../../methods/initMsgData.js';
import { webScoketMsg } from '../../methods/handleWebSocketMessage.js';
import groupNavBar from '../../components/groupNavBar.vue';
import formatMessageTime from '../../utils/formatMessageTime.js';
import { formatDistance } from '../../utils/distance.js';
import recordVioce from '../../components/recordVioce.vue';
import { play } from '../../methods/play.js';
import addFriend from '../../components/addFriend.vue';
import getMsgFromStore from '../../utils/getMsgFromStore';
import upDataMsgLastTime from '../../utils/upDataMsgLastTime';
import previewImageWithCache from'../../utils/previewImageWithCache.js'
const db = uniCloud.databaseForJQL();
const app = getApp().globalData;
import msg from '../../store/msg';



export default {
	components: {
		groupNavBar,
		// inputTab,
		groupInfo,
		recordVioce,
		addFriend,
		groupToolTab
	},
	data() {
		return {
			
			jionUser: {},
			isAddFriend: false,
			showJoinAnimation: false,
			members: [],
			isSpeak: false,
			isInputShow: true,
			scrollViewHeight: 0,
			scrollTop: 0,
			
			userInfo: {},
			progressPercent: 0,
			location: null,
			groupInfoShow: false,
			own: {},
			group: {},
			groupId: '',
			targetUser: {},
			audioContext: null,
			user: {},
			messages: [],
			toTarget: {},
			lastTimes: 0,
			viewId: '',
			showDeleteConfirm: -1 ,// 用于控制删除菜单的显示
			Imember:{}
		};
	},
	computed: {
		msglist() {
			if (!Array.isArray(this.messages)) {
				console.error('this.messages 不是一个数组');
				return [];
			}
			return this.messages.filter((item) => {
				if (item.toTarget && item.toTarget.targetType === '2') {
					return item.toTarget.targetId === this.group?.groupId;
				}
				return false;
			});
		},
	    join(){
			return msg.state.joinGroup
		},
		stateConfig(){
			return this.$store.state.msg.user.stateConfig
		}
		        		

	},
	watch: {
		msglist: {
			//当新消息进来时进行存储及已读操作
			handler(newMsg) {
				console.log("群信息",newMsg);
				if (newMsg.length === 0) {
					return;
				}
				this.$nextTick(() => {
					this.viewId = `msgall-${newMsg[newMsg.length - 1].timestamp}`;
				});
				const _this = this;
				const timestampMap = new Map(newMsg.map((msg) => [msg.timestamp, true]));
				const readedMsg = this.messages.map((item) => {
					if (timestampMap.has(item.timestamp)) {
						return {
							...item,
							isRead: true
						};
					}
					return item;
				});
				//通知会话列表
				uni.$emit('readmessages', readedMsg);
				console.log('+++++', this.group.groupId);
				upDataMsgLastTime(this.group.groupId, newMsg);

				// 保存到 Storage（可节流防抖）
				uni.getStorage({
					key: `msg_${this.toTarget.targetId}`,
					success: function (res) {
						let combinedData = [];
						const previousArray = res.data || [];

						// 先将旧数据复制到合并后的数组
						combinedData = [...previousArray];

						// 遍历新数据
						readedMsg.forEach((newMsg) => {
							const index = combinedData.findIndex((oldMsg) => oldMsg.timestamp === newMsg.timestamp);
							if (index !== -1) {
								combinedData[index] = newMsg;
							} else {
								combinedData.push(newMsg);
							}
						});

						// 将合并后的数据存入本地存储
						uni.setStorage({
							key: `msg_${_this.toTarget.targetId}`,
							data: combinedData,
							success: function () {
								console.log('存入本地存储时成功');
							},
							fail: function (error) {
								console.error('存入本地存储时出错:', error);
							}
						});
					},
					fail: function (err) {
						console.error('读取本地存储数据出错:', err);
						// 如果读取失败，直接将新数据存入本地存储(防止新用户时)
						uni.setStorage({
							key: `msg_${_this.toTarget.targetId}`,
							data: readedMsg,
							success: function () {
								console.log('已读消息数据已成功存入本地存储');
							},
							fail: function (error) {
								console.error('存入本地存储时出错:', error);
							}
						});
					}
				});
			},
			deep: true // 若需监听数组元素内部变化
		},
		Imember:{
			handler(newval){
				if(newval.isVote){
					uni.showToast({
						title:'您未被授权入群'
					})
				uni.navigateTo({
					url:'/pages/setDistance/setDistance'
				})
				}
			}
		},
		join:{
			handler(oldval,newval){
				console.log("从",oldval,'至',newval);
			},deep:true
		}
		
	},

	mounted() {
		 console.log('mounted');
		uni.$on('joinGroup', (res) => {
			console.log('加入群了吗？');
			if (res.groupId === this.group.groupId) {
				this.handleJoinGroup(res.jionUser);
			}
		});
		uni.$on('Imember',res=>this.Imember=res)
		this.adjustLayout();
		uni.$on('keyup', (res) => {
			this.keyboardHeight = res;
			this.scrollViewHeight = this.windowHight - res;

			this.$nextTick(() => {
				this.scrollTop += 999999;
			});
		});

		uni.$on('group_msg', (res) => {
			webScoketMsg(this, res);
		});
	},
	beforeDestroy() {
		uni.$off('joinGroup');
		uni.$off('Imember')
	},
	async onLoad(res) {
	
		this.user = app.user;
		const id = res.id;
		console.log('id.......', id);
		this.location = app.senderLocation;
		//获取附近群
		await this.getGroup(res.id);
		//加入就近群
		await this.joinGroup(id);
		//获取本地群消息
		this.messages = await getMsgFromStore(res.id);
	},
	onShow() {
		if (!app.ws) {
			uni.reLaunch({
				url: '/pages/start/start'
			});
		}
	},
	methods: {
		//初始化存储
		formatMessageTime,
		formatDistance,
	
		recordVioceClose() {
			(this.isSpeak = false), (this.isInputShow = true);
		},
		handleJoinGroup(user) {
			this.jionUser = user;
			this.showJoinAnimation = true;
			setTimeout(() => {
				this.showJoinAnimation = false;
			}, 4000);
		},

		TouchMain() {
			uni.$emit('mainPageClickEven');
			this.showDeleteConfirm = -1; // 点击其他区域隐藏删除菜单
		},
		handonPlay(i) {
			this.stateConfig.onPlay = !this.stateConfig.onPlay;
			if (!this.stateConfig.onPlay) {
				getApp().globalData.audioContext.stop();
				this.stateConfig.isPlaying = false;
			}
			if (this.stateConfig.onPlay) {
				console.log('断点1');
				play(this, i);
			}
		},
		handleAddFriend(item) {
			this.isAddFriend = true;
			this.userInfo.sendUserId = item.sendUserId;
			this.userInfo.nicName = item.nicName;
			this.userInfo.nicPic = item.nicPic;
			this.userInfo.userTel = item.userTel;
		},
		async joinGroup(id) {
			const joinData = {
				type: 'joinGroup',
				userId: app.user.userId,
				groupId: id
			};

			const res = await uniCloud.callFunction({
				name: 'web',
				data: joinData
			});
		},
		//获取群信息
		async getGroup(groupId) {
			try {
				const groupInfo = await db
					.collection('Group')
					.where({
						groupId: groupId
					})
					.get();
                 console.log(groupInfo);
			    if(groupInfo.data.length>0){
					this.group = groupInfo.data[0];
					this.toTarget.targetId = this.group.groupId;
					this.toTarget.targetType = '2';
					this.toTarget.targetName = this.group.groupName;
				}

				if (groupInfo.data.length > 0 && groupInfo.data[0].groupUser?.length > 0) {
					const groupUserList = groupInfo.data[0].groupUser;
										
					const userIds = groupUserList.map(user => user.userId).filter(Boolean);
						const getmember = await db
						.collection('linli-user')
						.where({
							userId: db.command.in(userIds)
						})
						.get();
			         const userMap = new Map();
			         getmember.data.forEach(user => {
			           userMap.set(user.userId, user);
			         });
			         
			         // 组合数据
			         const combinedList = groupUserList.map(groupUser => {
			           const userDetail = userMap.get(groupUser.userId) || {};
			           
			           return {
			             // 保留groupUser中的字段
			             ...groupUser,
			             ...userDetail
			           };
			         });
					this.members = combinedList;
					console.log('222222',this.members);
			    	this.Imember=	this.members.filter(item=>item.userId===app.user.userId)
								
				} else {
					this.members = [];
				}
                 console.log("ownid......",groupInfo.data[0].ownId);
				const getown = await db.collection('linli-user')
					.where({
						userId: groupInfo.data[0].ownId
					})
					.get();
					console.log('getown',getown);
				if (getown.data.length > 0) {
					this.own = getown.data[0];
				
				} else {
					this.own = {};
					uni.showToast({
						icon: 'none',
						title: '暂无群主'
					});
				}
			} catch (e) {
				console.log('错误', e);
			}
		},

		async adjustLayout() {
			try {
				const windowHeight = this.$store.state.msg.systemInfo.windowHeight - 155;
				this.windowHight = windowHeight;
				this.scrollViewHeight = windowHeight;
			} catch (error) {
				console.error('获取系统信息时出错:', error);
			}
		},
		isTimeshow(index) {
			if (index > 0) {
				if (this.msglist[index].timestamp - this.msglist[index - 1].timestamp < 300000) {
					return false;
				} else if (!this.msglist[index].timestamp) {
					return false;
				} else {
					return true;
				}
			}
			return true;
		},
		async sendText(msg) {
			sendText(this, msg);
		},
		//音频信息
		async voice_msg(voiceData) {
			voiceMsg(this, voiceData);
		},
		//图片信息
		async media_msg(mediapath) {
			mediaMsg(this, mediapath);
		},
		//视频信息
		async msg_video(item) {
			uni.showLoading({
				title: '视频上传中...'
			});
			const res = await videoMsg(this, item);
			if (res.data === 'ok') {
				uni.hideLoading();
			}
		},
		videoplay(url) {
			console.log('......', url);
			uni.navigateTo({
				url: `/pages/videoPlay/videoPlay?url=${url}`
			});
		},
        reSendMsg(item){
			const msg=item
			console.log(msg)
			reSendMsg(msg)
		},
		preview(img) {
			previewImageWithCache(this.msglist[img].content.mediaPath)
	
		},
		showDeleteMenu(item, index) {
			this.showDeleteConfirm = index;
		},
		deleteMessage(item, index) {
			// 从 messages 数组中删除消息
			this.messages = this.messages.filter((msg) => msg.timestamp !== item.timestamp);
			// 隐藏删除菜单
			this.showDeleteConfirm = -1;
			// 保存到本地存储
			uni.setStorage({
				key: `msg_${this.toTarget.targetId}`,
				data: this.messages,
				success: function () {
					console.log('删除消息后存入本地存储成功');
				},
				fail: function (error) {
					console.error('删除消息后存入本地存储出错:', error);
				}
			});
		},
		hangdleInputshow() {
			this.isInputShow = false;
			this.isSpeak = true;
		}
	}
};
</script>

<style lang="scss" scoped>
@keyframes leftToRight {
	0% {
		transform: translateX(0%);
		opacity: 0.8;
	}
	50% {
		transform: translateX(100%);
		opacity: 1;
	}
	100% {
		transform: translateX(400%);
		opacity: 0.8;
	}
}
.animated-element {
	display: flex;
	position: fixed;
	top: 200rpx; // 调整垂直位置
	left: 0;
	transform: translateX(-100%); // 初始位置在屏幕左侧外
	width: auto;
	padding: 10rpx 20rpx;
	background-color: rgba(255, 255, 255, 0.9);
	border-radius: 40rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	z-index: 999;
	white-space: nowrap; // 防止内容换行

	// 添加淡入动画
	animation: enterFromLeft 4s linear forwards;

	.imgs {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		margin-right: 10rpx;
	}

	.texts {
		font-size: 28rpx;
		color: #005500;
		line-height: 40rpx;
	}
}

// 定义新的动画
@keyframes enterFromLeft {
	0% {
		transform: translateX(-100%); // 初始位置在屏幕左侧外
		opacity: 0;
	}
	10% {
		transform: translateX(20rpx); // 进入屏幕内一点
		opacity: 1;
	}
	90% {
		transform: translateX(calc(100vw - 100% - 20rpx)); // 接近屏幕右侧
		opacity: 1;
	}
	100% {
		transform: translateX(100vw); // 移动到屏幕右侧外
		opacity: 0;
	}
}
.main {
	width: 100vw;
	height: 100vh;
	background-color: #f1f1f1;
}

.userpic {
	display: flex;
	flex-direction: column;
	justify-content: end;
	width: 120rpx;
	border-radius: 50%;
	margin-right: 32rpx;
}

.nicimg {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
}
.msgEdit {
	position: absolute;
	left: 0;
	top: 0;
	z-index: 999;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	width: 100rpx;
	height: 50rpx;
	border-radius: 5rpx;
	font-size: 28rpx;
	color: white;
	background-color: rgba(0, 0, 0, 0.7);
}

.scroll {
	display: flex;
	flex-direction: column;
	position: fixed;
	top: 100px;
	left: 0;
	justify-content: flex-end;
	width: 750rpx;
}
.timeformat {
	display: flex;
	justify-content: center;

	text-align: end;
	width: 200px;
	font-size: 20rpx;
	margin: 0 auto;
	padding-top: 30px;
	color: #969696;
}
.item {
	padding: 20rpx 20rpx 0 20rpx;
	align-items: flex-start;
	align-content: flex-start;
	color: #333;
	display: flex;
	flex-direction: row;
	flex-wrap: nowrap;
	justify-content: flex-start;
	.pic {
		width: 92rpx;
		height: 92rpx;
		border-radius: 15%;
		border: #e1e1e1 solid 1px;
	}

	.content {
		padding: 15rpx;
		border-radius: 4px;
		max-width: 500rpx;
		word-break: break-all;
		line-height: 45rpx;
		position: relative;
	}

	/* 收到的消息 */
	&.pull {
		.content {
			margin-left: 32rpx;
			background-color: #fff;

			&::after {
				content: '';
				display: block;
				width: 0;
				height: 0;
				border-top: 16rpx solid transparent;
				border-bottom: 16rpx solid transparent;
				border-right: 20rpx solid #fff;
				position: absolute;
				top: 30rpx;
				left: -18rpx;
			}
		}
	}

	/* 发出的消息 */
	&.push {
		/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
		flex-direction: row-reverse;

		.content {
			margin-right: 32rpx;
			background-color: #a0e959;

			&::after {
				content: '';
				display: block;
				width: 0;
				height: 0;
				border-top: 16rpx solid transparent;
				border-bottom: 16rpx solid transparent;
				border-left: 20rpx solid #a0e959;
				position: absolute;
				top: 30rpx;
				right: -18rpx;
			}
		}
	}
}

.unsend {
	display: flex;
	align-self: center;
	width: 120rpx;
	height: 30rpx;
	font-size: 28rpx;
	color: #333;

	image {
		width: 28rpx;
		height: 28rpx;
	}
}

.userId {
	color: #969696;
	font-size: 22rpx;
	padding-left: 30rpx;
	padding-bottom: 5rpx;
}
.media {
	display: flex;
	width: 300rpx;
	margin-right: 32rpx;
	margin-left: 32rpx;
	align-item: flex-start;
	justify-content: flex-start;
	position: relative;

	image {
		max-width: 300rpx;
		max-height: 400rpx;
	}
}
.video_v {
	width: 300rpx;
	height: 200rpx;

	border-radius: 25rpx;
}

.mark-image {
	position: absolute;
	max-width: 50%;
	max-height: 50%;
	:active {
		background-color: #3e2723;
	}
}
.video-thumbnail {
	position: relative;
	width: 300rpx;
	height: 200rpx;
}
.progress-bar {
	text-align: center;
	font-size: 25rpx;
	color: #007bff;
	height: 100%;
	padding: 0;
	overflow: hidden;
}

.progress {
	height: 100%;
	background-color: #007bff;
	height: 8rpx;
}

.image-container {
	position: relative;
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>
